<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Wallet;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Show;
use Encore\Admin\Widgets\InfoBox;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Table;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        // admin_success('Message...', 'success');

        return $content
            ->header('用户')
            ->description('用户管理')
            ->row(function (Row $row) {
                $row->column(3, function (Column $column) {
                    $total = User::count();
                    $infoBox = new InfoBox('会员总数', 'users', 'aqua', '/admin/users', $total);
                    $column->append($infoBox);
                });
                $row->column(3, function (Column $column) {
                    $today_total = User::whereDate('created_at', date('Y-m-d'))->count();
                    $infoBox = new InfoBox('今日新增用户', 'users', 'aqua', '/admin/todayUsers', $today_total);
                    $column->append($infoBox);
                });

            })
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑')
            ->description('编辑用户')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('创建用户')
            ->description('创建用户')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);

        $grid->id('Id');
        $grid->phone('手机号');
        $grid->email('邮箱');
        $grid->nickname('昵称')->expand(function ($model) {
            $comments = $model->where('id', $this->id)->get()->map(function ($item) {
                $item->is_member = $item->is_member?"是":"否";
                return $item->only(['id', 'real_name', 'is_member', 'province', 'city', 'weixin_nickname']);;
            });
            return new Table(['ID', '真实姓名', '是否会员', '省份', '城市', '微信昵称'], $comments->toArray());
        });

        $grid->avatar('头像')->lightbox(['width' => 50, 'height' => 50]);

        $grid->column('status', '用户状态')->editable('select', [1 => '正常', 2 => '冻结'])->sortable();
        $grid->code('邀请码');
        $grid->created_at('创建时间');
        $grid->updated_at('修改时间');
        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();
        });
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->like('phone', '手机号');       
            $filter->like('nickname', '昵称');
            $filter->between('created_at', '注册时间')->datetime();
            $filter->scope('今日新增', '今日新增')->whereDate('created_at', date('Y-m-d'));

        });
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->id('Id');
        $show->phone('Phone');
        $show->email('Email');
        $show->password('Password');
        $show->security('Security');
        $show->nickname('Nickname');
        $show->avatar('Avatar');
        $show->token('Token');
        $show->pid('Pid');
        $show->status('Status');
        $show->code('Code');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);

        $form->hidden('status')->default(1); //用户状态默认正常
        $form->hidden('hasPwd')->default(1); //用户状态默认正常
        $form->hidden('hasPayPwd')->default(1); //用户状态默认正常
        $form->hidden('hasPhone')->default(1); //用户状态默认正常
        $form->mobile('phone', '手机号')->required();
        $form->email('email', '邮箱')->required();
        $form->password('password', '密码')->required()->default('123456')->help('默认123456');
        $form->password('security', '交易密码')->required()->default('123456')->help('默认123456');
        $form->text('nickname', '昵称')->required();
        // $form->image('avatar', '头像')->move('images/avatars/' . date("Ym/d", time()))->uniqueName();
        $form->image('avatar', '头像')->move('images/avatars/' . date("Ym/d", time()))->uniqueName();
        $form->hidden('code')->default($this->str_rand());
        $form->saving(function (Form $form) {
            $form->password = bcrypt($form->password);
            $form->security = bcrypt($form->security);
            
        });
        $form->saved(function (Form $form) {
            $wallet = new Wallet();
            $user_id = $form->model()->id;
            $res = $wallet->hasUser($user_id);
            if (!$res) {
                $wallet->user_id = $user_id;
                $wallet->computing_power = 100;
                $wallet->save();
            }
            //@todo增加算力
        });

        return $form;
    }

    public function str_rand()
    {
        $str = mt_rand(100000, 999999);
        $count = User::where('code', $str)->count();
        if ($count > 0) {
            return $this->str_rand();
        } else {
            return strtolower($str);
        }
    }

}
